using System;
using System.Xml.Linq;
using Slf.Factories;

namespace Slf.Samples.CustomFactorySettings
{
  /// <summary>
  /// The factory, that creates a <see cref="ColoredConsoleLogger"/>, and initializes
  /// it with the settings of the configuration file.
  /// </summary>
  public class ColoredConsoleFactory : NamedLoggerFactoryBase<ColoredConsoleLogger>, IConfigurableLoggerFactory
  {
    //the colors that were read from the configuration file
    private ConsoleColor? foreground;
    private ConsoleColor? background;


    /// <summary>
    /// Inits the plug-in with configured factory data.
    /// </summary>
    /// <param name="factoryData">Retrieved factory settings.
    /// This parameter is null if no configuration at all
    /// was found.</param>
    public void Init(string factoryData)
    {
      //if there is nothing configured, just stick with the default
      if(String.IsNullOrEmpty(factoryData)) return;

      //parse XML configuration
      XElement element = XElement.Parse(factoryData);
      foreground = GetColor(element.Attribute("foreground"));
      background = GetColor(element.Attribute("background"));
    }


    /// <summary>
    /// Parses a given color if declared in the configuration file.
    /// </summary>
    private static ConsoleColor? GetColor(XAttribute attribute)
    {
      if (attribute == null || String.IsNullOrEmpty(attribute.Value))
      {
        return null;
      }
      
      return (ConsoleColor) Enum.Parse(typeof (ConsoleColor), attribute.Value);
    }


    /// <summary>
    /// Factory implementation, which creates a named logger instance and
    /// sets the foreground and background colors according to the configuration.
    /// </summary>
    protected override ColoredConsoleLogger CreateLogger(string name)
    {
      ColoredConsoleLogger logger = new ColoredConsoleLogger(name);
      logger.Foreground = foreground;
      logger.Background = background;

      return logger;
    }
  }
}